<?php
/*
    OpenLib
    Copyright (C) 2011  Michael Gukov, Pham Thi Thuy Duong

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/


namespace App\Controllers;

use Sun\Sun;
use Sun\Validators;
use Sun\Utils;
use App\Models;

// доступ для LIB
class Edition extends \Sun\Controller {
    public function __construct() {
        parent::__construct("Main");
    }

    public function MainAction($req) {
        if (isset($req->data['p'])){
            $v = $req->data['p'];
            $this->RenderView($v, $req->data);
        } else if (isset($req->data['m'])) {
            $v = $req->data['m'];
            $this->RenderViewScene($v, $req->data);
        } else {
            $this->RenderView("Edition\\Main", $req->data);
        }
    }

    //////////////////////////////////////////////////////////////
    /////////////////////// FIELDS ///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddFieldAction($req) {
        $edit = new Models\Edition();

        $validator = new Validators\NullValidator();

        $req->data['name'] = trim($req->data['name']);

        $res = new \Sun\Response();
        try {
            if (!$validator->Verify($req->data['name'], 'name'))
                throw new \Sun\Exception ("", 1);

            $edit->AddField($req->data);
            $res->STAT = 'OK';

        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $validator->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('name' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function AltFieldAction($req) {
        $edit = new Models\Edition();

        $validator = new Validators\NullValidator();

        $req->data['name'] = trim($req->data['name']);

        $res = new \Sun\Response();
        try {
            if (!$validator->Verify($req->data['name'], 'name'))
                throw new \Sun\Exception ("", 1);

            $edit->AltField($req->data);
            $res->STAT = 'OK';

        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $validator->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('name' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function DelFieldAction($req) {
        $res = new \Sun\Response();

        try {
            $edit = new Models\Edition();
            $edit->DelField($req->data);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
            $res->ERR = array('log' => 'Невозможно удалить поле, т.к. оно используется');
        }
        echo $res->ToJSON();
    }


    //////////////////////////////////////////////////////////////
    ///////////////////// EDITTYPES //////////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddEditTypeAction($req) {
        $validator = new Validators\ArrayValidator(
            new Validators\NullValidator());

        $req->data['name'] = trim($req->data['name']);
        $res = new \Sun\Response();
        try {
            if (!$validator->Verify($req->data))
                throw new \Sun\Exception('', 1);

            $edit = new Models\Edition();
            $fields = explode(",", $req->data['fields']);
            $edit->AddEditionType($req->data['name'], $fields);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $validator->Exceptions();
                    if (isset($res->ERR['fields']))
                        $res->data['ERR']['fields'] = 'Выбранно менее 1 атрибута';
                    break;
                default:
                    $res->ERR = array('name' => 'Имя не уникально');
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function AltEditTypeAction($req) {
        $validator = new Validators\ArrayValidator(
            new Validators\NullValidator());

        $req->data['name'] = trim($req->data['name']);
        $res = new \Sun\Response();
        try {
            if (!$validator->Verify($req->data))
                throw new \Sun\Exception('', 1);

            $edit = new Models\Edition();
            $fields = explode(",", $req->data['fields']);
            $edit->AltEditionType($req->data['type_id'], $req->data['name'], $fields);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $validator->Exceptions();
                    if (isset($res->ERR['fields']))
                        $res->data['ERR']['fields'] = 'Выбранно менее 1 атрибута';
                    break;
                default:
                    $res->ERR = array('name' => 'Имя не уникально');
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function DelEditTypeAction($req) {
        $res = new \Sun\Response();
        try {
            $edit = new Models\Edition();
            $edit->DelEditionType($req->data['type_id']);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
            $res->ERR = array('log' => 'Невозможно удалить тип, т.к. он используется');
        }
        echo $res->ToJSON();
    }


    //////////////////////////////////////////////////////////////
    ///////////////////// EDITIONS ///////////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddEditionAction($req) {
        $res = new \Sun\Response();
        $fval = \Sun\Utils::TrimArray(explode("[^&]", $req->data['fval']));
        try {

            $edit = new Models\Edition();
            $edit->AddEdition($req->data['type_id'],
                explode(",", $req->data['fid']), $fval, explode(",", $req->data['file']));
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function AltEditionAction($req) {

        $res = new \Sun\Response();
        $fval = \Sun\Utils::TrimArray(explode("[^&]", $req->data['fval']));
        try {

            $edit = new Models\Edition();
            $edit->AltEdition($req->data['edit_id'], $req->data['type_id'],
                explode(",", $req->data['fid']), $fval, explode(",", $req->data['file']));
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function DelEditionAction($req) {
        $res = new \Sun\Response();
        try {
            $edit = new Models\Edition();
            $edit->DelEdition($req->data['edit_id']);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
            $res->ERR = array('log' => 'Невозможно удалить издание, т.к. оно используется');
        }
        echo $res->ToJSON();
    }


    //////////////////////////////////////////////////////////////
    /////////////////////////INVENTARY////////////////////////////
    //////////////////////////////////////////////////////////////
    public function AddItemAction($req) {
        $res = new \Sun\Response();
        $kit = new Validators\ValidatorKit(array(
            'NumItems' => new Validators\NumValidator(),
            'Date' => new Validators\DateValidator()
        ));

        try {
            if (!$kit->Verify(array(
                'NumItems' => $req->data['NumItems'],
                'Date' => $req->data['Date'])))
                    throw new \Sun\Exception('', 1);
            $edit = new Models\Edition();
            $id = $edit->AddItem(
                    $req->data['EditId'],
                    $req->data['NumItems'],
                    $req->data['Date']);

            $res->STAT = 'OK';
            $res->ID = $id;

        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $kit->Exceptions();
                    break;
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }


    //////////////////////////////////////////////////////////////
    ///////////////////////////ORDERS/////////////////////////////
    //////////////////////////////////////////////////////////////

    public function AvailiableEditAction($req) {
        $edit = new Models\Edition();
        $item = $edit->GetAvailableItem($req->data['edit_id']);
        if ($item !== false)
           echo json_encode(array('STAT' => $item));
        else echo json_encode(array('STAT' => "NULL"));
    }

    public function IssueItemAction($req) {
        $res = new \Sun\Response();
        $edit = new Models\Edition();

        $valid = new Validators\ArrayValidator(
            new Validators\DateValidator());

        try {
            if (!$valid->Verify(Utils::ValuesAt(
                    $req->data, array('iss_date', 'ret_date'))))
                throw new \Sun\Exception ('', 1);

            if (strtotime($req->data['iss_date']) >= strtotime($req->data['ret_date']))
                throw new \Sun\Exception ('', 2);

            $edit->IssueItem($req->data);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $valid->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('log' => 'Дата выдачи больше даты возврата');
                    break;
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    public function ReturnItemAction($req) {
        $res = new \Sun\Response();
        $edit = new Models\Edition();
        try {
            $edit->ReturnItem($req->data);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';

            switch ($e->getCode()) {
                case 1:
                    $res->ERR = $valid->Exceptions();
                    break;
                case 2:
                    $res->ERR = array('log' => 'Дата выдачи больше даты возврата');
                    break;
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }

    //////////////////////////////////////////////////////////////
    ///////////////////////////CATALOG////////////////////////////
    //////////////////////////////////////////////////////////////

    public function AltCatalogFieldAction($req) {
        $res = new \Sun\Response();
        try {
            if (empty($req->data['fields']))
                throw new \Sun\Exception('', 1);
            $fields = explode(',', $req->data['fields']);
            $edit = new Models\Edition();
            $edit->SetCatalofFields($fields);
            $res->STAT = 'OK';
        } catch (\Exception $e) {
            $res->STAT = 'ERR';
            switch ($e->getCode()) {
                case 1:
                    $res->ERR = array('log' => 'Выбранно менее 1 атрибута');
                    break;
                default:
                    $res->ERR = array('log' => $e->getMessage());
                    break;
            }
        }
        echo $res->ToJSON();
    }
}



